from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
import os

# Create your models here.

class Antique(models.Model):
    DYNASTY_CHOICES = [
        ('shang', '商朝'),
        ('zhou', '周朝'),
        ('qin', '秦朝'),
        ('han', '汉朝'),
        ('tang', '唐朝'),
        ('song', '宋朝'),
        ('yuan', '元朝'),
        ('ming_hongwu', '明洪武'),
        ('ming_yongle', '明永乐'),
        ('ming_xuande', '明宣德'),
        ('ming_chenghua', '明成化'),
        ('ming_hongzhi', '明弘治'),
        ('ming_zhengde', '明正德'),
        ('ming_jiajing', '明嘉靖'),
        ('ming_longqing', '明隆庆'),
        ('ming_wanli', '明万历'),
        ('ming_tianqi', '明天启'),
        ('ming_chongzhen', '明崇祯'),
        ('qing_shunzhi', '清顺治'),
        ('qing_kangxi', '清康熙'),
        ('qing_yongzheng', '清雍正'),
        ('qing_qianlong', '清乾隆'),
        ('qing_jiaqing', '清嘉庆'),
        ('qing_daoguang', '清道光'),
        ('qing_xianfeng', '清咸丰'),
        ('qing_tongzhi', '清同治'),
        ('qing_guangxu', '清光绪'),
        ('qing_xuantong', '清宣统'),
        ('minguo', '民国'),
        ('other', '其他'),
    ]
    
    CONDITION_CHOICES = [
        ('excellent', '优'),
        ('good', '良'),
        ('fair', '中'),
        ('poor', '差'),
    ]

    PROCESS_CHOICES = [
        ('qingci', '青瓷'),
        ('miseci', '秘色瓷'),
        ('qingbaici', '青白瓷'),
        ('luanbaiyou', '卵白釉瓷'),
        ('tianbai', '甜白'),
        ('jihong', '祭红'),
        ('jiaotai', '绞胎'),
        ('linglongci', '玲珑瓷'),
        ('youxiacai', '釉下彩'),
        ('qinghua', '青花'),
        ('youlihong', '釉里红'),
        ('youshangcai', '釉上彩'),
        ('jinjiacai', '金加彩'),
        ('doucai', '斗彩'),
        ('susaicai', '素三彩'),
        ('wucai', '五彩'),
        ('fencai', '粉彩'),
        ('falangcai', '珐琅彩'),
        ('other', '其他'),
    ]

    SHAPE_CHOICES = [
        ('wan', '碗'),
        ('bei', '杯'),
        ('pan', '盘'),
        ('hu', '壶'),
        ('lu', '炉'),
        ('he', '盒'),
        ('guan', '罐'),
        ('pen', '盆'),
        ('ping', '瓶'),
        ('yi', '匜'),
        ('zhen', '枕'),
        ('xi', '洗'),
        ('zun', '尊'),
        ('other', '其他'),
    ]

    KILN_CHOICES = [
        ('geyao', '哥窑'),
        ('junyao', '均窑'),
        ('ruyao', '汝窑'),
        ('dingyao', '定窑'),
        ('other', '其他'),
    ]

    number = models.CharField(max_length=50, verbose_name='编号', blank=True, null=True)
    name = models.CharField(max_length=200, verbose_name='名称')
    description = models.TextField(verbose_name='描述', blank=True)
    dynasty = models.CharField(max_length=50, choices=DYNASTY_CHOICES, default='other', verbose_name='朝代')
    condition = models.CharField(max_length=50, choices=CONDITION_CHOICES, default='good', verbose_name='品相')
    size = models.CharField(max_length=100, verbose_name='尺寸', blank=True)
    process = models.CharField(max_length=50, choices=PROCESS_CHOICES, verbose_name='工艺分类', blank=True)
    shape = models.CharField(max_length=50, choices=SHAPE_CHOICES, verbose_name='器型分类', blank=True)
    kiln = models.CharField(max_length=50, choices=KILN_CHOICES, verbose_name='窑口分类', blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    order = models.IntegerField(default=0, verbose_name='排序')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '古董'
        verbose_name_plural = '古董'
        ordering = ['order', '-created_at']

    def __str__(self):
        return f"{self.name} ({self.get_dynasty_display()})"

class AntiqueImage(models.Model):
    antique = models.ForeignKey(Antique, on_delete=models.CASCADE, related_name='images', verbose_name='古董')
    image = models.ImageField(upload_to='antiques/images/', verbose_name='图片')
    thumbnail = models.ImageField(upload_to='antiques/thumbnails/', verbose_name='缩略图', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    def save(self, *args, **kwargs):
        if not self.thumbnail and self.image:
            # 创建缩略图
            img = Image.open(self.image)
            # 设置缩略图的最大尺寸
            max_size = (300, 300)
            img.thumbnail(max_size, Image.Resampling.LANCZOS)
            
            # 保存缩略图
            thumb_io = BytesIO()
            img.save(thumb_io, format='JPEG', quality=85)
            thumb_io.seek(0)
            
            # 生成缩略图文件名
            thumb_name = f"thumb_{os.path.basename(self.image.name)}"
            self.thumbnail.save(thumb_name, ContentFile(thumb_io.getvalue()), save=False)
        
        super().save(*args, **kwargs)

    class Meta:
        verbose_name = '古董图片'
        verbose_name_plural = '古董图片'
        ordering = ['created_at']
